package com.changgou.pay.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.pay.service.WXPayService;
import com.github.wxpay.sdk.WXPay;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.awt.*;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@Service
public class WXPayServiceImpl implements WXPayService {

    @Autowired
    private WXPay wxPay;

    @Value("${wxpay.notify_url}")
    private String notify_url;

    // 统一下单接口调用
    @Override
    public Map nativePay(String orderId, Integer money) {

        try {
            // 封装请求参数
            Map<String, String> map = new HashMap();
            // 商品描述
            map.put("body", "畅购");
            // 商品订单号
            map.put("out_trade_no", orderId);
            // 总钱数
            BigDecimal bigDecimal = new BigDecimal("0.01");
            BigDecimal fen = bigDecimal.multiply(new BigDecimal("100")); //1.00
            fen = fen.setScale(0, BigDecimal.ROUND_UP);
            map.put("total_fee", String.valueOf(fen));
            // 终端ip
            map.put("spbill_create_ip", "127.0.0.1");
            // 通知地址
            map.put("notify_url", notify_url);
            // 支付类型
            map.put("trade_type", "NATIVE");
            Map<String, String> result = wxPay.unifiedOrder(map);
            System.out.println("wxPay返回的数值" + JSON.toJSON(result));

            return result;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    // 根据订单id查询微信支付结果
    @Override
    public Map queryOrder(String orderId) {

        try {
            Map<String, String> map = new HashMap<>();
            map.put("out_trade_no", orderId);
            Map<String, String> result = wxPay.orderQuery(map);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    // 关闭订单
    @Override
    public Map closeOrder(String orderId) {

        try {
            Map map = new HashMap();
            map.put("ut_trade_no", orderId);

            return wxPay.closeOrder(map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
